//
//  PersonalMessageViewController.m
//  iStore
//
//  Created by MacDev on 15/4/16.
//  Copyright (c) 2015年 mirrtalk. All rights reserved.
//

#import "PersonalMessageViewController.h"
#import "StoreManagerViewController.h"
#import "NewLogViewController.h"
#import "RequestEngine.h"

#define kPhoneBak  @"^1[3|4|5|7|8][0-9]\\d{8}$"
#define kIDCard  @"^(\\d{14}|\\d{17})(\\d|[xX])$"
#define kEmail @"^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$"
@interface PersonalMessageViewController ()<UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextFieldDelegate>
{
    UIImage *selectImageFront;
    UIImage *selectImageBack;
    UITextField *currentTextfield;
    BOOL keyboardIsShown;
    NSInteger chooose;
    __weak IBOutlet UIButton *choose;
}
@property (weak, nonatomic) IBOutlet UIButton *senChoose;
@end

@implementation PersonalMessageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"个人信息填写";
    self.navigationItem.leftBarButtonItem = nil;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"下一步" style:UIBarButtonItemStylePlain target:self action:@selector(goNextView)];
    _userName.delegate = self;
    _userId.delegate = self;

    _email.delegate = self;
    _userId.keyboardType = UIKeyboardTypeAlphabet;

    
    
    [_senChoose setBackgroundImage:[UIImage imageNamed:@"Rectangle_6"] forState:UIControlStateHighlighted];
    [choose setBackgroundImage:[UIImage imageNamed:@"Rectangle_6"] forState:UIControlStateHighlighted];
    
    
}
- (void)goNextView
{
    /*phone
     phoneBak
     password
     IDNumber
     email
     userName
     appKey
     platformType*/

    [self testFileDidFinish];
    NSString *user = _userName.text;
    NSString *userId = _userId.text;

    NSString *email = _email.text;
    NSString *userID = [[NSUserDefaults standardUserDefaults] objectForKey:kUserId];
    NSString *type = [[NSUserDefaults standardUserDefaults]objectForKey:KplatformType];
//    NSData *data = [[NSData alloc]init];
//    if (UIImagePNGRepresentation(selectImage)) {
//        data = UIImagePNGRepresentation(selectImage);
//    }
//    else if(UIImageJPEGRepresentation(selectImage, 1)){
//        data = UIImageJPEGRepresentation(selectImage, 1);
//    }
    if (user.length == 0) {
        alert(@"请输入姓名");
        return;
    }
    else if (user.length > 10) {
        alert(@"您输入的名字太长")
        return;
    }
    if (selectImageFront == nil || selectImageBack == nil) {
        alert(@"请选则上传的证件照");
        return;
    }

    if (![self regexFlagWith:kIDCard withParameter:userId]) {
        alert(@"您输入的身份证不符合规范，请重新输入");
        return;
    }
    if (email.length) {
        if (![self regexFlagWith:kEmail withParameter:email]) {
            alert(@"您输入的邮箱不符合规范，请重新输入");
            return;
        }
    }
    
    [self activityStart];
    
    [RequestEngine userUpdateWithDic:@{
                                       @"userID":userID,
                                       @"IDNumber":userId,
                                       @"email":email,
                                       @"userName":user,
                                       @"appKey":@"IOS",
                                       @"platformType":type,
                                       
                                       } imageArray:@[selectImageFront,selectImageBack] completed:^(NSString *errorcode, NSDictionary *resultDict) {
                                           [self activityStop];
                                           if ([errorcode isEqualToString:@"0"]) {
                                               
                                             NewLogViewController  *loginVc = [[NewLogViewController alloc] init];
                                               [self.navigationController pushViewController:loginVc animated:YES];
                                               
                                           }
                                else if([errorcode isEqualToString:@"-1"]){
                                    
                                    alert(@"请检查网络");
                                    return;
                                }
                                else{
                                    NSString *result = [NSString stringWithFormat:@"%@",resultDict];
                                    alert(result);
                                    return;
                                }
                            }];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark --输入框上移--
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    [UIView animateWithDuration:0.3 animations:^{
        CGRect frame = self.view.frame;
        frame.origin.y = -216;
        self.view.frame = frame;
    }];
    return YES;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self testFileDidFinish];
}

- (void)testFileDidFinish
{
    [UIView animateWithDuration:0.3 animations:^{
        CGRect frame =self.view.frame;
        frame.origin.y = 0.0;
        self.view.frame = frame;
    }];
    [_email resignFirstResponder];
    [_userName resignFirstResponder];

    [_userId resignFirstResponder];
}
#pragma mark -- 选择图片上传 --
- (IBAction)choosePicture:(UIButton *)sender {
    chooose = sender.tag;
    
    UIActionSheet *actionSheet=[[UIActionSheet alloc]initWithTitle:@"选择" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"相册" otherButtonTitles:@"拍照", nil];
    [actionSheet showInView:self.view];

}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
            //从相册提取
        {
            UIImagePickerController *imgPicker = [[UIImagePickerController alloc] init];
            [imgPicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
            [imgPicker setDelegate:self];
            [self presentViewController:imgPicker animated:YES completion:nil];
        }
            break;
            
            //拍照
        case 1:
        {
            UIImagePickerController *imgPicker = [[UIImagePickerController alloc] init];
            [imgPicker setSourceType:UIImagePickerControllerSourceTypeCamera];
            [imgPicker setDelegate:self];
            [self presentViewController:imgPicker animated:YES completion:nil];
        }
            break;
    }
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    if (chooose == 101) {
        [_userImagefront setImage:image];
        selectImageFront = image;
    }
    else if (chooose == 102) {
        [_userImageBack setImage:image];
        selectImageBack = image;
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}


//正则表达式的判断
- (BOOL) regexFlagWith:(NSString *)regex withParameter:(NSString *)parameter{
    
    NSPredicate *pass = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    
    return [pass evaluateWithObject:parameter];
    
}
@end
